package com.bjpowerndoe.ylb.web.controller;

import cn.hutool.core.util.PhoneUtil;
import com.bjpowerndoe.ylb.common.AppConsts;
import com.bjpowerndoe.ylb.web.enums.CodeEnum;
import com.bjpowerndoe.ylb.web.model.CommonResult;
import com.bjpowerndoe.ylb.web.service.inter.SmsManagerService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 *
 */
@Api(tags = "短信")
@RequiredArgsConstructor
@RestController
public class SmsController {


    private final SmsManagerService smsManagerService;
    /**
     * action: LOGIN 表示登录
     *         REGISTER 表注册
     * @param phone
     * @param action
     * @return
     */
    @ApiOperation(value = "发送注册验证码",notes = "登录，注册都使用此接口")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "phone",value = "手机号",required = true),
            @ApiImplicitParam(name = "action",value = "LOGIN或者REGISTER",required = true),
    })
    @GetMapping("/sms/code")
    public CommonResult sendSms(String phone,String action){
        CommonResult commonResult = CommonResult.fail(CodeEnum.PHONE_FORMAT_ERR);
        if(PhoneUtil.isPhone(phone)){
            //对ACTION判断
            if(AppConsts.SMS_ACTION_LOGIN.equalsIgnoreCase(action) ||
                    AppConsts.SMS_ACTION_REGISTER.equalsIgnoreCase(action)){
                //判断已有短信是否可用
                boolean useOrSend = smsManagerService.checkSmsRegister(phone,action);
                if( useOrSend ){
                    //提示，可以继续使用
                    commonResult = CommonResult.fail(CodeEnum.SMS_CODE_USE);
                } else {
                    //重新发送证码
                    boolean smsResult = smsManagerService.sendSms(phone, action);
                    if(smsResult){
                        commonResult = CommonResult.ok();
                    } else {
                        commonResult = CommonResult.fail(CodeEnum.SMS_SEND_RETRY);
                    }
                }
            } else {
                commonResult = CommonResult.fail(CodeEnum.REQUEST_PARAM_ERR);
            }
        }
        return commonResult;
    }
}
